package com.yun.image.yunimagebackend.aop;

import com.yun.image.yunimagebackend.annotation.AuthCheck;
import com.yun.image.yunimagebackend.exception.BusinessException;
import com.yun.image.yunimagebackend.exception.ErrorCode;
import com.yun.image.yunimagebackend.model.entity.User;
import com.yun.image.yunimagebackend.model.enums.UserRoleEnum;
import com.yun.image.yunimagebackend.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 权限校验
     * @param joinPoint 切点
     * @param authCheck 注解
     * @return
     * @throws Throwable
     */
    @Around(value = "@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint,AuthCheck authCheck ) throws Throwable {
        String mustRole = authCheck.mustRole();
        //获取request
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取当前登录用户
        User user = userService.getLoginUser(request);

        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        // 判断是否有权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(user.getUserRole());
        if (userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //如果需要管理员权限，则必须是管理员
        if (mustRoleEnum.equals(UserRoleEnum.ADMIN) && !userRoleEnum.equals(UserRoleEnum.ADMIN)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        return joinPoint.proceed();
    }
}
